package com.jdew.thkj.base;


import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.fastjson.JSONObject;
import com.jaeger.library.StatusBarUtil;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.JDProductDetailActivity;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.TbProductDetailActivity;
import com.jdew.thkj.bean.TokenBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.ActivityManagerUtils;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.WrapContentLinearLayoutManager;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.pgyersdk.crash.PgyCrashManager;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by yangyang on 2017/9/7.
 */

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
    /**
     * 当前Activity渲染的视图View
     **/
    private View mContextView = null;
    protected final String TAG = this.getClass().getSimpleName();
    public Bundle savedInstanceState;
    public String resultString = "";
    public SharedPreferences sp;
    public SharedPreferences.Editor editor;
    private String ItemId;
    private String e;
    private String tkl;
    public Dialog mWeiboDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        changeStatusBarTextColor(true);
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;
        mContextView = LayoutInflater.from(this).inflate(bindLayout(), null);
        setContentView(mContextView);
        ActivityManagerUtils.pushActivity(this);
        StatusBarUtil.setTransparentForImageView(this, null);
        ButterKnife.bind(this);
        PgyCrashManager.register(this);
        initView(mContextView);
    }

    /**
     * [绑定布局]
     *
     * @return
     */
    public abstract int bindLayout(

    );

    /**
     * 沉浸式状态栏
     */
    private void changeStatusBarTextColor(boolean isBlack) {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.theme_color));
            if (isBlack) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏黑色字体
            } else {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);//恢复状态栏白色字体
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * [初始化控件]
     *
     * @param view
     */
    public abstract void initView(final View view);

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }

    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    public void hideWriting(View view) {
        ((InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(view.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    protected void onResume() {
        super.onResume();
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        getToken();
        ItemId = null;
        pasteToResult();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AlibcTradeSDK.destory();
        ActivityManagerUtils.popActivity(this);
        PgyCrashManager.unregister();
    }

    public <T extends RecyclerView.Adapter> void setRcycleview(RecyclerView rcycleview, T adapter) {
        rcycleview.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rcycleview.setAdapter(adapter);
    }

    public void IntelligentSearch(final String message) {
        new CommonDialog.Builder(this, 0)
                .setMessage(message)
                .setMessageGravity()
                .setCanceledOnTouchOutside(false)
                .setdialogPostive("搜索", 0, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        resultString = "";
                        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboardManager.setPrimaryClip(ClipData.newPlainText(null, ""));
                        if (clipboardManager.hasPrimaryClip()) {
                            clipboardManager.getPrimaryClip().getItemAt(0).getText();
                        }
                        toSearch(message);
                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        resultString = "";
                        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboardManager.setPrimaryClip(ClipData.newPlainText(null, ""));
                        if (clipboardManager.hasPrimaryClip()) {
                            clipboardManager.getPrimaryClip().getItemAt(0).getText();
                        }
                    }
                }).show();
    }

    private void pasteToResult() {
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        // 检查剪贴板是否有内容
        if (!cm.hasPrimaryClip()) {

        } else {
            ClipData clipData = cm.getPrimaryClip();
            if (null != clipData) {
                int count = clipData.getItemCount();

                for (int i = 0; i < count; ++i) {

                    ClipData.Item item = clipData.getItemAt(i);
                    CharSequence str = item.coerceToText(this);
                    resultString += str;
                }
            }
        }
        if ((((resultString.contains("【") && resultString.contains("】") && (resultString.contains("http://") || resultString.contains("https://")))) || ((resultString.contains("https:") ||
                resultString.contains("http:")) && (resultString.contains("&id=") || resultString.contains("/i") || resultString.contains("?id=") || resultString.contains("itemId=") || (resultString.contains("?e="))))) || ((resultString.contains("￥") || resultString.contains("€") || resultString.contains("《") || resultString.contains("$") || resultString.contains("(") || resultString.contains("₰") || resultString.contains("₴") || resultString.contains("¢"))) || resultString.contains("淘♂寳♀") || resultString.contains("jd.com")) {
            IntelligentSearch(resultString);
        }

    }

    public void toSearch(String resultString) {
        if (sp.getString("SpareTwo", "").equals("")) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
            toset("检测到您还没有绑定上级,请到我的页面绑定上级");
            return;
        }
        if (!RegexValidateUtils.isFastClick()) {
            return;
        }
        String result = resultString;
        String str = RegexValidateUtils.removeNonBmpUnicode(result).replace("#", "");
        if (str.contains("￥") || str.contains("€") || str.contains("《") || str.contains("$") || str.contains("(") || str.contains("₰") || str.contains("₴") || str.contains("¢")) {
            if (str.contains("这段描述")) {
                tkl = str.substring(str.indexOf("这段描述"));
            } else if (str.contains("拷贝")) {
                tkl = str.substring(str.indexOf("拷贝"));
            } else {
                tkl = str;
            }
        } else {
            tkl = str;
        }
        if (str.contains("u.jd.com")) {
            try {
                ItemId = URLEncoder.encode(str, "utf-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            toJDetail();
            return;
        }
        if (!(((str.contains("https:") || str.contains("http:"))) && str.contains("&id=") || str.contains("/i") || str.contains("?id=") || str.contains("itemId=") || str.contains("?e=") || str.contains("jd.com"))) {
            parseTkl();
        } else if ((str.contains("https:") || str.contains("http:") || str.contains("jd.com"))) {
            try {
                if (str.contains("?e=")) {
                    e = str.substring(str.indexOf("?e=") + 3);
                    getItemId(e);
                    return;
                } else if (str.contains("&id=") || str.contains("/i") || str.contains("jd.com") || str.contains("?id=") || str.contains("itemId=") || str.contains("sku=") || str.contains("skuid=")) {
                    ItemId = getHttpItemId(str);
                    if (str.contains("jd.com")) {
                        toJDetail();
                        return;
                    } else {
                        toTBDetail();
                    }
                } else {
                    ToastUtils.getInstance(this).showMessage("请输入正确的链接或淘口令!");
                    return;
                }
            } catch (Exception e) {
                ToastUtils.getInstance(this).showMessage("该商品暂无佣金计划或已下架!");
                return;
            }

            if (sp.getString("userPhone", "").equals("")) {
                startActivity(new Intent(this, LoginActivity.class));
                return;
            } else if (sp.getString("UserSjPhone", "").equals("") && (sp.getString("SpareTwo", "").equals("0") || sp.getString("SpareTwo", "").equals("2"))) {
                toset("检测到您还没有绑定上级,请到我的页面绑定上级");
            } else {
                toTBDetail();
            }
        } else {
            ToastUtils.getInstance(this).showMessage("未查询到该商品!");
        }
    }


    public void toset(String message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(message)
                .setdialogPostive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                }).show();
    }

    public void parseTkl() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetTkl(tkl, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "tkl" + tkl)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (null != obj && obj.get("code").equals("0")) {
                    ItemId = getHttpItemId(obj.getString("data"));
                } else {
                    ToastUtils.getInstance(BaseActivity.this).showMessage("此淘口令无法解析!");
                }
                if (sp.getString("userPhone", "").equals("")) {
                    startActivity(new Intent(BaseActivity.this, LoginActivity.class));
                    return;
                } else if (sp.getString("UserSjPhone", "").equals("") && (sp.getString("SpareTwo", "").equals("0") || sp.getString("SpareTwo", "").equals("2"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else if (null == ItemId) {
                    ToastUtils.getInstance(BaseActivity.this).showMessage("此淘口令无法解析!");
                } else if (ItemId.contains("?e=")) {
                    e = ItemId.substring(ItemId.indexOf("?e=") + 3);
                    getItemId(e);
                } else if (ItemId.contains("&e=")) {
                    e = ItemId.substring(ItemId.indexOf("&e=") + 3);
                    getItemId(e);
                } else {
                    toTBDetail();
                }
            }
        });
    }

    private String getHttpItemId(String str) {
        Pattern p = Pattern.compile("\\d+");
        if (null == str) {
            return null;
        } else if (str.contains("&id=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("&id=")).substring(4));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("?id=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("?id=")).substring(4));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("itemId=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("itemId=")).substring(7));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("sku=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("sku=")).substring(4));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("skuid=")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("skuid=")).substring(6));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("product/")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("product/")).substring(8));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("?e=")) {
            return str;
        } else if (str.contains("&e=")) {
            return str;
        } else if (str.contains("/i")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("/i")).substring(2));
            if (m.find()) {
                return m.group();
            }
        } else if (str.contains("jd.com/")) {
            Matcher m = p.matcher(str.substring(str.lastIndexOf("jd.com/")).substring(7));
            if (m.find()) {
                return m.group();
            }
        } else {
            return null;
        }
        return null;
    }

    public void toTBDetail() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != ItemId) {
                    if (TAG.equals("TbProductDetailActivity")) {
                        finish();
                    }
                    Bundle b = new Bundle();
                    b.putSerializable("itemId", ItemId);
                    startActivity(TbProductDetailActivity.class, b);
                } else {
                    ToastUtils.getInstance(BaseActivity.this).showMessage("请输入正确的链接或淘口令!");
                }
            }
        });
    }

    public void toJDetail() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (TAG.equals("JDProductDetailActivity")) {
                    finish();
                }
                if (null != ItemId) {
                    Bundle b = new Bundle();
                    b.putSerializable("itemId", ItemId);
                    startActivity(JDProductDetailActivity.class, b);
                } else {
                    ToastUtils.getInstance(BaseActivity.this).showMessage("请输入正确的京东链接!");
                }
            }
        });
    }

    public void getItemId(String e) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetTBItemId(e, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "e" + e)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    ItemId = obj.getString("data");
                    toTBDetail();
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        resultString = "";
        if (null != mWeiboDialog) {
            mWeiboDialog.cancel();
        }
    }

    public void getToken() {
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetToken(RegexValidateUtils.getUniquePsuedoID(), RegexValidateUtils.getUniquePsuedoID(), RegexValidateUtils.getTime13(), RegexValidateUtils.getRandom10()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TokenBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(TokenBean bean) {
                if (bean.getStatusCode().equals("0")) {
                    String token = bean.getData().getSignToken();
                    editor.putString("SignToken", token);
                    editor.apply();
                }
            }
        });
    }
}